<template>
  <button class="btn-ghost"
    :class="classType"
    :disabled="classType === 'disabled'"
    @click.prevent="onStartCountDown">
    {{text}}
  </button>
</template>

<script>
  export default {
    props: {
      time: {
        type: Number,
        default: 60
      },
      isReset: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        msgCodeTime: this.time,
        classType: 'main',
        text: '获取验证码'
      }
    },
    methods: {
      onStartCountDown() {
        if (this.msgCodeTime === 0) {
          this.classType = 'main'
          this.text = '获取验证码'
          this.msgCodeTime = this.time
        } else {
          this.classType = 'disabled'
          this.text = `重新发送${this.msgCodeTime}s`
          this.msgCodeTime--
          setTimeout(() => {
            this.onStartCountDown()
          }, 1000)
        }
      }
    },
    watch: {
      isReset(newVal, oldVal) {
        if (newVal) {
          this.msgCodeTime = 0
          this.$parent.isReset = false
        }
      }
    }
  }
</script>